package com.jsz.peini.controller.app;

import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jsz.peini.bean.coupon.CouponInfo;
import com.jsz.peini.bean.order.ScoreHistory;
import com.jsz.peini.bean.order.ScoreHistoryExample;
import com.jsz.peini.bean.order.ScoreHistoryExample.Criteria;
import com.jsz.peini.common.constants.Constants;
import com.jsz.peini.common.util.DateTimeUtils;
import com.jsz.peini.common.util.PeiniUtils;
import com.jsz.peini.mapper.coupon.CouponInfoMapper;
import com.jsz.peini.mapper.order.ScoreHistoryMapper;

@Controller
public class ScoreHistoryController {
	private static final Logger logger = LoggerFactory.getLogger(ScoreHistoryController.class);
	@Resource
	private ScoreHistoryMapper scoreHistoryMapper;
	@Resource
	private CouponInfoMapper couponInfoMapper;

	@ResponseBody
	@RequestMapping(value="/getScoreHistoryList")
	public Object list(HttpServletRequest request,
			@RequestParam(value="type",required=false) Integer opType, //1收入；0支出
			@RequestParam(value="userId",required=true) String userToken,
			@RequestParam(value="page",required=true) Integer page, 
			@RequestParam(value="rows",required=true) Integer rows
			){
		JSONObject object = new JSONObject();
		JSONArray array = new JSONArray();
		try {
			JSONObject obj = PeiniUtils.validToken(userToken);
			if(obj.getInteger("resultCode") != 1){
				return obj;
			}
			String userId = obj.getString("userId");
			
			ScoreHistoryExample scoreHistoryExample = new ScoreHistoryExample();
			Criteria criteria = scoreHistoryExample.createCriteria();
			if(opType != null){
				criteria.andOpTypeEqualTo(opType);
			}
			criteria.andUserIdEqualTo(userId);
			criteria.andIsDelEqualTo(1);
			scoreHistoryExample.setOrderByClause("create_time desc");
			
			PageHelper.startPage(page, rows);
			List<ScoreHistory> list = scoreHistoryMapper.selectByExample(scoreHistoryExample);
			PageInfo<ScoreHistory> prePage = new PageInfo<>(list);
			list = prePage.getList();
			for (ScoreHistory his : list) {
				obj = new JSONObject();
				obj.put("hisId", his.getHisId());
				obj.put("valNum", (his.getOpType() == 1 ? "+" : "-")+his.getValNum());
				obj.put("createTime", DateTimeUtils.formatDateTime2String(his.getCreateTime(), "yyyy-MM-dd"));
				obj.put("type", his.getHisType());
				obj.put("paramId", his.getParamId());
				
				switch (his.getHisType()) {
				case 1:
					obj.put("imgSrc", "");
					obj.put("name", "【系统】签到奖励");
					break;
				case 2:
					
					break;
				case 3://兑换优惠券
					
					CouponInfo info = couponInfoMapper.selectByPrimaryKey(Integer.parseInt(his.getParamId()));
					if(info!=null)
					{
						obj.put("imgSrc", StringUtils.trimToEmpty(info.getCouponSrc()));
						obj.put("name", "【兑换】"+info.getCouponName());
					}
					break;
				default:
					break;
				}
				array.add(obj);
			}
			
			object.put("data", array);
			object.put("resultCode", Constants.SUCCESS);
			object.put("resultDesc", Constants.SUCCESS_DESC);
		} catch (Exception e) {
			object.put("resultCode", Constants.EXCEPTION);
			object.put("resultDesc", Constants.EXCEPTION_DESC);
			logger.error(e.getMessage(),e);
		}
		return object;
	}
	
	@Transactional
	@ResponseBody
	@RequestMapping(value="/delScoreHistory")
	public Object del(HttpServletRequest request,
			@RequestParam(value="idStr",required=true) String idStr, //积分历史id列表，逗号分割
			@RequestParam(value="userId",required=false) String userToken
			){
		JSONObject object = new JSONObject();
		JSONArray array = new JSONArray();
		try {
			JSONObject obj = PeiniUtils.validToken(userToken);
			if(obj.getInteger("resultCode") != 1){
				return obj;
			}
			String userId = obj.getString("userId");
			
			if(StringUtils.isBlank(idStr)){
				object.put("resultCode", Constants.FAIL);
				object.put("resultDesc", "参数为空");
				return object;
			}
			
			String [] ids = idStr.split(",");
			List<String> idList = Arrays.asList(ids);
			
			ScoreHistoryExample scoreHistoryExample = new ScoreHistoryExample();
			Criteria criteria = scoreHistoryExample.createCriteria();
			criteria.andUserIdEqualTo(userId);
			criteria.andHisIdIn(idList);
			scoreHistoryExample.setOrderByClause("create_time desc");
			List<ScoreHistory> list = scoreHistoryMapper.selectByExample(scoreHistoryExample);
			if(list.size() != idList.size()){
				object.put("resultCode", Constants.FAIL);
				object.put("resultDesc", "参数错误");
				return object;
			}
			
			for (ScoreHistory his : list) {
				his.setIsDel(0);
				scoreHistoryMapper.updateByPrimaryKey(his);
			}
			
			object.put("resultCode", Constants.SUCCESS);
			object.put("resultDesc", Constants.SUCCESS_DESC);
		} catch (Exception e) {
			object.put("resultCode", Constants.EXCEPTION);
			object.put("resultDesc", Constants.EXCEPTION_DESC);
			logger.error(e.getMessage(),e);
		}
		return object;
	}
}
